package com.lcm.weam.controller.sys;


import com.lcm.weam.entity.resp.Result;
import com.lcm.weam.entity.resp.ResultCode;
import com.lcm.weam.entity.sys.User;
import com.lcm.weam.service.sys.UserService;
import com.lcm.weam.util.RSAUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.Map;

/**
 * 匿名访问接口（登录、注册和登出）
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/anon")
public class AnonController {

    private static final int HASHITERATIONS = 3;

    @Autowired
    private UserService userService;

    //未登录成功和未授权时返回的接口（shiro配置中调用）
    @RequestMapping(value = "/autherror", method = RequestMethod.GET)
    public Result autherror(String code) {
        return "1".equals(code) ? new Result(ResultCode.UNAUTHENTICATED) : new Result(ResultCode.UNAUTHORISE);
    }

    /**
     * 登录接口，通过 mobile 和 password 登录，以及一个rememberMe 布尔值
     *             返回成功则返回sessionId，未成功则返回手机号密码错误
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody Map<String, Object> map) {
        String mobile = (String) map.get("mobile");
        String password = (String) map.get("password");
        Object rememberMe = map.get("rememberMe");
        UsernamePasswordToken token = new UsernamePasswordToken(mobile, new Md5Hash(password, mobile, HASHITERATIONS).toString());
        Subject subject = SecurityUtils.getSubject();
        if (rememberMe != null) {
            token.setRememberMe((boolean) rememberMe);
        }
        try {
            subject.login(token);
            return new Result(ResultCode.SUCCESS, subject.getSession().getId());
        } catch (Exception e) {
            return new Result(ResultCode.MOBILE_OR_PASSWORD_ERROR);
        }
    }

    /*
        手机验证码登录
            但发送验证码需要电信服务费，未使用
     */
/*    @RequestMapping(value = "/loginByCode", method = RequestMethod.POST)
    public Result loginByCode(@RequestBody Map<String, Object> map) {
        String mobile = (String) map.get("mobile");
        boolean rememberMe = (boolean)map.get("rememberMe");
        String code = (String)map.get("code");
        MobileAndVerificationCodeToken token = new MobileAndVerificationCodeToken(mobile, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return new Result(ResultCode.SUCCESS, subject.getSession().getId());
        }catch (Exception e) {
            return new Result(ResultCode.VERIFICATION_CODE_ERROR);
        }

    }*/

    //登出
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new Result(ResultCode.SUCCESS);
    }

    //后台查看session
    @RequestMapping(value = "/showSession", method = RequestMethod.POST)
    public Result show(String data, HttpSession session) {
        System.out.println(data);
        Enumeration<String> names = session.getAttributeNames();
        while (names.hasMoreElements()) {
            String s = names.nextElement();
            Object o = session.getAttribute(s);
            System.out.println(s + "=" + o);
        }
        String sessionId = session.getId();
        return new Result(ResultCode.SUCCESS, sessionId);
    }


    /**
     * 注册新用户（未认证）
     * 传递：用户名、手机号、用户密码、邮箱必填，其余选填，用户头像不填
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result register(@RequestBody User user) {
        user.setPassword(new Md5Hash(user.getPassword(), user.getMobile(), HASHITERATIONS).toString());
        userService.register(user);
        return new Result(ResultCode.SUCCESS);
    }


    /**
     * 获取当前登录用户信息
     */
    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    public Result profile() {
        //获取session中的安全数据
        Object o = SecurityUtils.getSubject().getPrincipal();
        return new Result(ResultCode.SUCCESS, o);
    }

    @RequestMapping(value = "/exchangeKey", method = RequestMethod.POST)
    public Result exchangeKey(){
        return new Result(ResultCode.SUCCESS, RSAUtil.getPublicKey());
    }


}
